package com.ruoyi.wxhouse.service.imp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.house.domain.YjzUser;
import com.ruoyi.house.mapper.YjzUserMapper;
import com.ruoyi.wxhouse.mapper.YjzWxUserMapper;
import com.ruoyi.wxhouse.service.IWxUserService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 微信小程序用户服务实现
 */
@Service
public class WxUserServiceImpl implements IWxUserService {

    @Autowired
    private YjzWxUserMapper wxUserMapper;

    @Autowired
    private YjzUserMapper yjzWxUserMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     *  登录
     *  @param loginData 微信登录凭证
     *  @return 登录结果
     * */
    @Override
    public AjaxResult login(Map<String, Object> loginData) {
        try {
            // 修复后代码：
            String code = (String) loginData.get("code");
            // 调用微信接口获取session_key和openid
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String openid = session.getOpenid();

            // 添加openid
            loginData.put("openid", openid);
            // 查找或创建用户
            YjzUser user = findOrCreateUser(loginData);

            // 生成自定义token
            String token = generateToken(user.getId(), openid);

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("userInfo", user);

            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("登录失败：" + e.getMessage());
        }
    }

    /**
     *  获取用户信息
     *  @param userId 用户ID
     *  @return 用户信息
     * */
    @Override
    public YjzUser getUserInfo(Long userId) {
        return yjzWxUserMapper.selectById(userId);
    }


    /**
     *  查找或创建用户
     *  @param loginData
     *  @return 用户信息
     * */
    private YjzUser findOrCreateUser(Map<String, Object> loginData) {
        // 获取openid
        String openid = (String) loginData.get("openid");
        YjzUser user = yjzWxUserMapper.selectOne(
                new LambdaQueryWrapper<YjzUser>()
                        .eq(YjzUser::getOpenid, openid)
        );
        if (user == null) {
            user = new YjzUser();
            user.setOpenid(openid);
            // 添加用户信息
            user.setAvatar((String) loginData.get("avatar"));
            user.setNickname((String) loginData.get("nickname"));
            yjzWxUserMapper.insert(user);
        }
        return user;
    }

    private String generateToken(Long userId, String openid) {
        String token = UUID.randomUUID().toString().replace("-", "");
        // 存入Redis，7天有效
        redisTemplate.opsForValue().set("wx_token:" + token, userId.toString(), 7, java.util.concurrent.TimeUnit.DAYS);
        return token;
    }

}